package org.icress.fusion.moc

import org.icress.fusion.shiro.User
import org.apache.shiro.SecurityUtils
import org.springframework.transaction.annotation.*

class TbService {

    static transactional = true

    @Transactional(readOnly = true)
    def list(Object params) {
        def tbInstanceList =Tb.withCriteria{
            if(params.line && params.line != "-")
                like("tb010", params.line + "%")
            inList("status", ["未生产", "已发料", "生产中"])
            firstResult(params.offset ? params.int('offset') : 0)
            maxResults(params.max ? params.int('max') : 100)
            if(params.sort && params.order)order(params.sort, params.order)
        }
        return tbInstanceList
    }
    
    @Transactional(readOnly = true)
    def count(Object params) {
        def tbInstanceTotal = Tb.withCriteria{
            projections {
                count('id')
            }
            if(params.line && params.line != "-")
                like("tb010", params.line + "%")
            inList("status", ["未生产", "已发料", "生产中"])
        }[0]
        return tbInstanceTotal
    }
    
    def save(Tb tbInstance, Object params, boolean flush) {
        //get user
        def currentUser = User.findByUsername( SecurityUtils.getSubject().getPrincipal() )
        
        tbInstance.createdBy = currentUser
        tbInstance.lastModifiedBy = currentUser
        tbInstance.owner = currentUser
        
        def success = tbInstance.save(flush: flush)
        return success
    }
    
    def update(Tb tbInstance, Object params, boolean flush) {
        //get user
        def currentUser = User.findByUsername( SecurityUtils.getSubject().getPrincipal() )
        
        tbInstance.lastModifiedBy = currentUser

        def success = tbInstance.save(flush: flush)
        return success
    }

    def get(Object id) {
        def tbInstance = Tb.get(id)
        return tbInstance
    }
    
    def delete(Tb tbInstance, boolean flush) {
        def success = tbInstance.delete(flush: flush)
        return success
    }

}
